<?php
@session_start();
@error_reporting(0);
@ini_set('display_errors', 'Off');
define('SENLIN_CLIENT_VERSION', '1.4.0');
if (!file_exists('../config.php')) { 
    die("出现错误！配置文件丢失，请先完成安装。"); 
}
require_once '../config.php';
if (file_exists('../common/version.php')) { 
    require_once '../common/version.php'; 
} else { 
    define('SENLIN_CLIENT_VERSION', '0.0.0'); 
}
if (!isset($_SESSION['admin_id'])) { 
    header('Location: login.php'); 
    exit; 
}
if (isset($_GET['action']) && $_GET['action'] === 'logout') { 
    session_destroy(); 
    header('Location: login.php'); 
    exit; 
}
$username = htmlspecialchars($_SESSION['admin_username']);
$stats = [
    'today_calls' => 0,
    'total_apis' => 0,
    'total_users' => 0,
    'total_calls_all' => 0,
    'pending_feedback' => 0,
    'success_orders' => 0,
    'failed_orders' => 0,
    'pending_orders' => 0,
    'today_income' => 0
];
$server_info = [
    'php_version' => PHP_VERSION,
    'server_software' => substr($_SERVER['SERVER_SOFTWARE'], 0, 25) . '...',
    'mysql_version' => 'N/A',
    'load_avg' => 'N/A'
];
$chart_data_json = '{"labels":[],"data":[]}';
$update_available = false;
$pdo = null;

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET, 
        DB_USER, 
        DB_PASS
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stats['today_calls'] = $pdo->query("SELECT COUNT(*) FROM sl_api_logs WHERE DATE(request_time) = CURDATE()")->fetchColumn();
    $stats['total_apis'] = $pdo->query("SELECT COUNT(*) FROM sl_apis")->fetchColumn();
    $stats['total_users'] = $pdo->query("SELECT COUNT(*) FROM sl_users")->fetchColumn();
    $stats['total_calls_all'] = $pdo->query("SELECT SUM(total_calls) FROM sl_apis")->fetchColumn() ?: 0;
    $stats['pending_feedback'] = $pdo->query("SELECT COUNT(*) FROM sl_feedback WHERE status = 'pending'")->fetchColumn();
    $stats['success_orders'] = $pdo->query("
        SELECT COUNT(*) 
        FROM sl_orders 
        WHERE status = 'paid' 
        AND DATE(created_at) = CURDATE()
    ")->fetchColumn();
    $stats['failed_orders'] = $pdo->query("
        SELECT COUNT(*) 
        FROM sl_orders 
        WHERE status = 'failed' 
        AND DATE(created_at) = CURDATE()
    ")->fetchColumn();
    $stats['pending_orders'] = $pdo->query("
        SELECT COUNT(*) 
        FROM sl_orders 
        WHERE status = 'pending'
    ")->fetchColumn();
    $stats['today_income'] = $pdo->query("
        SELECT SUM(amount) 
        FROM sl_orders 
        WHERE status = 'paid' 
        AND DATE(created_at) = CURDATE()
    ")->fetchColumn() ?: 0;
    $server_info['mysql_version'] = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
    $chart_query = $pdo->query("
        SELECT DATE(request_time) as day, COUNT(*) as calls 
        FROM sl_api_logs 
        WHERE request_time >= CURDATE() - INTERVAL 30 DAY 
        GROUP BY day 
        ORDER BY day ASC
    ");    
    $chart_raw_data = $chart_query->fetchAll(PDO::FETCH_ASSOC);
    $chart_labels = []; 
    $chart_values = [];    
    $period = new DatePeriod(
        new DateTime('-29 days'), 
        new DateInterval('P1D'), 
        new DateTime('+1 day')
    );    
    $dates = [];
    foreach($period as $date) { 
        $dates[$date->format('Y-m-d')] = 0; 
    }    
    foreach($chart_raw_data as $row) { 
        $dates[$row['day']] = (int)$row['calls']; 
    }    
    foreach($dates as $day => $calls) { 
        $chart_labels[] = date('m-d', strtotime($day)); 
        $chart_values[] = $calls; 
    }    
    $chart_data_json = json_encode(['labels' => $chart_labels, 'data' => $chart_values]);

} catch (PDOException $e) { 
    error_log("[" . date('Y-m-d H:i:s') . "] 数据库错误: " . $e->getMessage() . "\n", 3, "../logs/db_errors.log");
    foreach ($stats as &$stat) {
        $stat = 0;
    }
    $server_info['mysql_version'] = '连接失败';
}
if (function_exists('sys_getloadavg')) { 
    $load = sys_getloadavg(); 
    $server_info['load_avg'] = round($load[0], 2); 
}

$current_page = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
<link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
</head>
  
<body>
<div class="container-fluid">

  <div class="row">

    <div class="col-md-6 col-xl-3">
      <div class="card bg-primary text-white">
        <div class="card-body">
          <div class="d-flex justify-content-between">
            <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
              <i class="mdi mdi-code-array fs-4"></i>
            </span>
            <span class="fs-4 scroll-numbers"><?php echo number_format($stats['today_calls']); ?></span>
          </div>
          <div class="text-end">今日调用</div>
        </div>
      </div>
    </div>

<div class="col-md-6 col-xl-3">
  <div class="card bg-info text-white">
    <div class="card-body">
      <div class="d-flex justify-content-between">
        <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
          <i class="mdi mdi-currency-cny fs-4"></i>
        </span>
        <span class="fs-4 scroll-numbers"><?php echo number_format($stats['today_income'] ?? 0, 2); ?></span>
      </div>
      <div class="text-end">今日收益(元)</div>
    </div>
  </div>
</div>

  	<div class="col-md-6 col-xl-3">
  	  <div class="card bg-danger text-white">
  	    <div class="card-body">
  	      <div class="d-flex justify-content-between">
  	        <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
              <i class="mdi mdi-api fs-4"></i>
            </span>
  	        <span class="fs-4 scroll-numbers"><?php echo number_format($stats['total_apis']); ?></span>
  	      </div>
  	      <div class="text-end">API总数</div>
  	    </div>
  	  </div>
  	</div>

  	<div class="col-md-6 col-xl-3">
  	  <div class="card bg-success text-white">
  	    <div class="card-body">
  	      <div class="d-flex justify-content-between">
  	        <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
              <i class="mdi mdi-account fs-4"></i>
            </span>
  	        <span class="fs-4 scroll-numbers"><?php echo number_format($stats['total_users']); ?></span>
  	      </div>
  	      <div class="text-end">用户总数</div>
  	    </div>
  	  </div>
  	</div>

  	<div class="col-md-6 col-xl-3">
  	  <div class="card bg-pink text-white">
  	    <div class="card-body">
  	      <div class="d-flex justify-content-between">
  	        <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
              <i class="mdi mdi-sync fs-4"></i>
            </span>
  	        <span class="fs-4 scroll-numbers"><?php echo number_format($stats['total_calls_all']); ?></span>
  	      </div>
  	      <div class="text-end">总调用数</div>
  	    </div>
  	  </div>
  	</div>

  	<div class="col-md-6 col-xl-3">
  	  <div class="card bg-purple text-white">
  	    <div class="card-body">
  	      <div class="d-flex justify-content-between">
  	        <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
              <i class="mdi mdi-thumb-up-outline fs-4"></i>
            </span>
  	        <span class="fs-4 scroll-numbers"><?php echo number_format($stats['pending_feedback']); ?></span>
  	      </div>
  	      <div class="text-end">待处理反馈</div>
  	    </div>
  	  </div>
  	</div>
  	
<!-- 在现有的卡片行中添加以下三个卡片 -->

<div class="col-md-6 col-xl-3">
  <div class="card bg-success text-white">
    <div class="card-body">
      <div class="d-flex justify-content-between">
        <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
          <i class="mdi mdi-check-circle fs-4"></i>
        </span>
        <span class="fs-4 scroll-numbers"><?php echo number_format($stats['success_orders'] ?? 0); ?></span>
      </div>
      <div class="text-end">成功订单</div>
    </div>
  </div>
</div>

<div class="col-md-6 col-xl-3">
  <div class="card bg-danger text-white">
    <div class="card-body">
      <div class="d-flex justify-content-between">
        <span class="avatar-md rounded-circle bg-white bg-opacity-25 avatar-box">
          <i class="mdi mdi-close-circle fs-4"></i>
        </span>
        <span class="fs-4 scroll-numbers"><?php echo number_format($stats['failed_orders'] ?? 0); ?></span>
      </div>
      <div class="text-end">失败订单</div>
    </div>
  </div>
</div>

  </div>

<div class="row">    
  <div class="col-lg-12">
    <div class="card">
      <header class="card-header">
        <div class="card-title">系统信息</div>
      </header>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover">
            <thead>
              <tr>
                <th>项目</th>
                <th>值</th>
              </tr>
            </thead>
            <tbody>
              <?php
              // 1. 基础信息
              $sysInfo = [
                '系统版本' => 'v'.SENLIN_CLIENT_VERSION,
                '服务器' => $_SERVER['SERVER_SOFTWARE'] ?? '未知',
                'PHP版本' => phpversion(),
                'MySQL版本' => $server_info['mysql_version'] ?? '未知',
                '系统负载' => $server_info['load_avg'] ?? '未知'
              ];

              // 2. 操作系统信息
              if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                $sysInfo['操作系统'] = 'Windows';
              } else {
                $sysInfo['操作系统'] = php_uname('s').' '.php_uname('r');
              }

              // 3. CPU信息 (Linux)
              if (is_readable('/proc/cpuinfo')) {
                $cpuinfo = file_get_contents('/proc/cpuinfo');
                preg_match_all('/model name\s*:\s*(.+)/', $cpuinfo, $matches);
                $cpuModel = isset($matches[1][0]) ? $matches[1][0] : '未知';
                $cpuCount = count($matches[1]);
                $sysInfo['CPU信息'] = "{$cpuCount}核 - {$cpuModel}";
              }

              // 4. 内存信息 (Linux)
              if (is_readable('/proc/meminfo')) {
                $meminfo = file_get_contents('/proc/meminfo');
                preg_match('/MemTotal:\s+(\d+)/', $meminfo, $matches);
                $total = round($matches[1]/1024);
                preg_match('/MemAvailable:\s+(\d+)/', $meminfo, $matches);
                $available = round($matches[1]/1024);
                $used = $total - $available;
                $percent = round(($used/$total)*100);
                $sysInfo['内存使用'] = "{$used}MB / {$total}MB ({$percent}%)";
              }

              // 5. 磁盘信息
              $diskTotal = round(disk_total_space('/')/(1024*1024*1024), 2);
              $diskFree = round(disk_free_space('/')/(1024*1024*1024), 2);
              $diskUsed = $diskTotal - $diskFree;
              $diskPercent = round(($diskUsed/$diskTotal)*100);
              $sysInfo['磁盘空间'] = "{$diskUsed}GB / {$diskTotal}GB ({$diskPercent}%)";

              // 6. PHP配置
              $sysInfo['PHP内存限制'] = ini_get('memory_limit');
              $sysInfo['PHP最大执行时间'] = ini_get('max_execution_time').'秒';

              // 7. 网络信息
              $sysInfo['服务器IP'] = $_SERVER['SERVER_ADDR'] ?? '未知';
              $sysInfo['客户端IP'] = $_SERVER['REMOTE_ADDR'] ?? '未知';
              
              // 获取公网IP (需要服务器能访问外网)
              if (function_exists('curl_init')) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://api.ipify.org');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $publicIP = curl_exec($ch);
                curl_close($ch);
                $sysInfo['公网IP'] = $publicIP ?: '获取失败';
              }

              // 8. 数据库信息 (需要MySQL连接)
              if (isset($db_connection)) {
                $result = $db_connection->query("SHOW STATUS LIKE 'Threads_connected'");
                $row = $result->fetch_assoc();
                $sysInfo['MySQL连接数'] = $row['Value'] ?? '未知';
              }

              // 输出所有信息
              foreach ($sysInfo as $name => $value) {
                echo "<tr><td>{$name}</td><td>{$value}</td></tr>";
              }
              ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
                
  <div class="row">

  	<div class="col-lg-12">
  	  <div class="card">
  	    <header class="card-header">
  	      <div class="card-title">项目信息</div>
  	    </header>
  		<div class="card-body">
  		  <div class="table-responsive">
  		    <table class="table table-hover">
  		      <thead>
  		        <tr>
  		          <th>#</th>
  		          <th>项目名称</th>
  		          <th>开始日期</th>
  		          <th>截止日期</th>
  		          <th>状态</th>
  		          <th>进度</th>
  		        </tr>
  		      </thead>
  			  <tbody>
  			    <tr>
  			      <td>1</td>
  			      <td>重构后台UI</td>
  			      <td>17/07/2025</td>
  			      <td>18/07/2025</td>
  			      <td><span class="badge bg-success">已完成</span></td>
  			      <td>
  			        <div class="progress progress-xs">
  			          <div class="progress-bar progress-bar-striped bg-success" style="width: 100%;"></div>
  			        </div>
  			      </td>
  			    </tr>
  			    <tr>
  			      <td>2</td>
  			      <td>增加前台模板UI切换功能</td>
  			      <td>17/07/2025</td>
  			      <td>17/12/2025</td>
  			      <td><span class="badge bg-success">已完成</span></td>
  			      <td>
  			        <div class="progress progress-xs">
  			          <div class="progress-bar progress-bar-striped bg-success" style="width: 99%;"></div>
  			        </div>
  			      </td>
  			    </tr>
  			    			    <tr>
  			      <td>2</td>
  			      <td>前台API在线测试自动获取登录用户key</td>
  			      <td>18/07/2025</td>
  			      <td>17/12/2025</td>
  			      <td><span class="badge bg-warning">进行中</span></td>
  			      <td>
  			        <div class="progress progress-xs">
  			          <div class="progress-bar progress-bar-striped bg-warning" style="width: 99%;"></div>
  			        </div>
  			      </td>
  			    </tr>
  			  </tbody>
            </table>
  	      </div>
  	    </div>
  	  </div>
    </div>

  </div>

</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/chart.min.js"></script>
<!-- 数字动态滚动增加效果 -->
<script type="text/javascript" src="../assets/js/scroll-numbers.js"></script>
<!--引入chart插件js-->
<script type="text/javascript" src="../assets/js/main.min.js"></script>
</body>
</html>